package com.xiaoshangkou.hellopra.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoshangkou.hellopra.bean.PermissionWithStatus;
import com.xiaoshangkou.hellopra.mapper.PermissionMapper;
import com.xiaoshangkou.hellopra.mapper.RoleMapper;
import com.xiaoshangkou.hellopra.pojo.Permission;
import com.xiaoshangkou.hellopra.pojo.Role;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 关于数据库中的角色服务层
 *
 */
@Service
public class RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    //分页查询角色
    public Page<Role> findPage(int page,int size){
        Page selectPage = roleMapper.selectPage(new Page(page, size), null);
        return selectPage;
    }

    //新增角色
    public void add(Role role){
        roleMapper.insert(role);
    }

    //删除角色
    public void delete(Integer rid){
        roleMapper.deleteById(rid);
    }

    //根据rid获取角色内容
    public Role findById(Integer rid){
        return roleMapper.selectById(rid);
    }

    //更新角色内容
    public void update(Role role){
        roleMapper.updateById(role);
    }

    //查找所有权限，以及角色拥有的权限
    public List<PermissionWithStatus> findPermission(Integer rid){
        List<Permission> permissions = permissionMapper.selectList(null);//查询所有权限
        List<Integer> permissionIdByRole = permissionMapper.findPermissionIdByRole(rid);//查询角色拥有的权限id
        List<PermissionWithStatus> permissionWithStatuses=new ArrayList<>();//创建带有状态的权限集合
        for (Permission permission : permissions) {
            PermissionWithStatus permissionWithStatus=new PermissionWithStatus();
            //将普通权限类复制给带有状态的权限类
            BeanUtils.copyProperties(permission,permissionWithStatus);//当权限循环到角色拥有的权限时
            if (permissionIdByRole.contains(permission.getPeid())){
                permissionWithStatus.setPermissionHas(true);
            }else {
                permissionWithStatus.setPermissionHas(false);
            }
            permissionWithStatuses.add(permissionWithStatus);
        }

        return permissionWithStatuses;
    }

    //给角色重新赋予权限
    public void updatePermissioon(Integer[] ids,Integer rid){
        //先删除所有权限再重新赋予用户选中的权限
        roleMapper.deleteRoleAllPermission(rid);//删除所有权限
        //赋予权限
        for (Integer peid : ids) {
            roleMapper.addRolePermission(rid,peid);
        }
    }

}
